package com.jdyinfo.ic.integration.eweixin;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jdyinfo.ic.eweixin.WorkWeixinConstants;
import com.jdyinfo.ic.eweixin.WorkWeixinScrmConfig;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Component
public class WorkWeixinDao {
	Logger logger = LoggerFactory.getLogger(WorkWeixinDao.class);
	
	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	
	@Autowired
	WorkWeixinScrmConfig workWeixinScrmConfig;
	
	@Autowired
	OkHttpClient okHttpClient;
	
	public String retrieveContactAccessToken() {
		String baseUrl = WorkWeixinConstants.baseUrl;
		String tokenPath = WorkWeixinConstants.tokenGetPath;
		
		String corpId = workWeixinScrmConfig.getCorpId();
		String contactSecret = workWeixinScrmConfig.getContactSecret();
		Map<String,String> paramMap = new HashMap<String, String>();
		paramMap.put("corpid", corpId);
		paramMap.put("corpsecret", contactSecret);
		
		String tokenApiUrl = buildApiUrl(baseUrl, tokenPath, paramMap);
		
		Request request = new Request.Builder()
			      .url(tokenApiUrl)
			      .build();
		String reposeString = null;
		try {
			Response response = okHttpClient.newCall(request).execute();
			reposeString = response.body().string();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return reposeString;
	}
	
	public String retrieveAppAccessToken() {
		String baseUrl = WorkWeixinConstants.baseUrl;
		String tokenPath = WorkWeixinConstants.tokenGetPath;
		
		String corpId = workWeixinScrmConfig.getCorpId();
		String appSecret = workWeixinScrmConfig.getAppSecret();
		Map<String,String> paramMap = new HashMap<String, String>();
		paramMap.put("corpid", corpId);
		paramMap.put("corpsecret", appSecret);
		
		String tokenApiUrl = buildApiUrl(baseUrl, tokenPath, paramMap);
		
		Request request = new Request.Builder()
			      .url(tokenApiUrl)
			      .build();
		String reposeString = null;
		try {
			Response response = okHttpClient.newCall(request).execute();
			reposeString = response.body().string();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return reposeString;
	}
	
	public String retrieveUserById(String userId) {
		String baseUrl = WorkWeixinConstants.baseUrl;
		String userGetPath = WorkWeixinConstants.userGetPath;
		
		String accessToken = "uwhr2YRko3cWg0e1SlxphMeL4AZ9crB9BTwEt99X9o1rECdX0q_zaPKikvTaiZw134sZumJvTQJ8oUZeyy3NY4cYGvgtTTfpsR_dpOC4z4-OGmCTL_DLBry3dPhorRpsGnh3RIk7Kk_pkYt2RljvWAQ2lhuXZFGmSbF8xqWIistdiw2CLkqZhu51B-yWk0R9hinaaEf_UHjHs3B4TF8urQ";
		Map<String,String> paramMap = new HashMap<String, String>();
		paramMap.put("access_token", accessToken);
		paramMap.put("userid", userId);
		
		String userGetApiUrl = buildApiUrl(baseUrl, userGetPath, paramMap);
		
		Request request = new Request.Builder()
			      .url(userGetApiUrl)
			      .build();
		String reposeString = null;
		try {
			Response response = okHttpClient.newCall(request).execute();
			reposeString = response.body().string();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return reposeString;
	}
	
	public String retrieveUserByDepartment(String departmentId) {
		String baseUrl = WorkWeixinConstants.baseUrl;
		String userSimpleListGetPath = WorkWeixinConstants.userSimpleListGetPath;
		
		String accessToken = "uwhr2YRko3cWg0e1SlxphMeL4AZ9crB9BTwEt99X9o1rECdX0q_zaPKikvTaiZw134sZumJvTQJ8oUZeyy3NY4cYGvgtTTfpsR_dpOC4z4-OGmCTL_DLBry3dPhorRpsGnh3RIk7Kk_pkYt2RljvWAQ2lhuXZFGmSbF8xqWIistdiw2CLkqZhu51B-yWk0R9hinaaEf_UHjHs3B4TF8urQ";
		Map<String,String> paramMap = new HashMap<String, String>();
		paramMap.put("access_token", accessToken);
		paramMap.put("department_id", departmentId);
		paramMap.put("fetch_child", "1");
		
		String userSimpleListGetApiUrl = buildApiUrl(baseUrl, userSimpleListGetPath, paramMap);
		
		Request request = new Request.Builder()
			      .url(userSimpleListGetApiUrl)
			      .build();
		String reposeString = null;
		try {
			Response response = okHttpClient.newCall(request).execute();
			reposeString = response.body().string();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return reposeString;
	}
	
	public String retrieveDepartments() {
		String baseUrl = WorkWeixinConstants.baseUrl;
		String departmentListGetPath = WorkWeixinConstants.departmentListGetPath;
		
		String accessToken = "uwhr2YRko3cWg0e1SlxphMeL4AZ9crB9BTwEt99X9o1rECdX0q_zaPKikvTaiZw134sZumJvTQJ8oUZeyy3NY4cYGvgtTTfpsR_dpOC4z4-OGmCTL_DLBry3dPhorRpsGnh3RIk7Kk_pkYt2RljvWAQ2lhuXZFGmSbF8xqWIistdiw2CLkqZhu51B-yWk0R9hinaaEf_UHjHs3B4TF8urQ";
		Map<String,String> paramMap = new HashMap<String, String>();
		paramMap.put("access_token", accessToken);
		
		String userSimpleListGetApiUrl = buildApiUrl(baseUrl, departmentListGetPath, paramMap);
		
		Request request = new Request.Builder()
			      .url(userSimpleListGetApiUrl)
			      .build();
		String reposeString = null;
		try {
			Response response = okHttpClient.newCall(request).execute();
			reposeString = response.body().string();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return reposeString;
	}
	
	public String retrieveDepartmentById(String departmentId) {
		String baseUrl = WorkWeixinConstants.baseUrl;
		String departmentListGetPath = WorkWeixinConstants.departmentListGetPath;
		
		String accessToken = "uwhr2YRko3cWg0e1SlxphMeL4AZ9crB9BTwEt99X9o1rECdX0q_zaPKikvTaiZw134sZumJvTQJ8oUZeyy3NY4cYGvgtTTfpsR_dpOC4z4-OGmCTL_DLBry3dPhorRpsGnh3RIk7Kk_pkYt2RljvWAQ2lhuXZFGmSbF8xqWIistdiw2CLkqZhu51B-yWk0R9hinaaEf_UHjHs3B4TF8urQ";
		Map<String,String> paramMap = new HashMap<String, String>();
		paramMap.put("access_token", accessToken);
		paramMap.put("id", departmentId);
		
		String userSimpleListGetApiUrl = buildApiUrl(baseUrl, departmentListGetPath, paramMap);
		
		Request request = new Request.Builder()
			      .url(userSimpleListGetApiUrl)
			      .build();
		String reposeString = null;
		try {
			Response response = okHttpClient.newCall(request).execute();
			reposeString = response.body().string();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return reposeString;
	}
	
	public String createDepartment(String json) {
		String baseUrl = WorkWeixinConstants.baseUrl;
		String departmentCreatePostPath = WorkWeixinConstants.departmentCreatePostPath;
		
		String accessToken = "uwhr2YRko3cWg0e1SlxphMeL4AZ9crB9BTwEt99X9o1rECdX0q_zaPKikvTaiZw134sZumJvTQJ8oUZeyy3NY4cYGvgtTTfpsR_dpOC4z4-OGmCTL_DLBry3dPhorRpsGnh3RIk7Kk_pkYt2RljvWAQ2lhuXZFGmSbF8xqWIistdiw2CLkqZhu51B-yWk0R9hinaaEf_UHjHs3B4TF8urQ";
		Map<String,String> paramMap = new HashMap<String, String>();
		paramMap.put("access_token", accessToken);
		
		String departmentCreatePostApiUrl = buildApiUrl(baseUrl, departmentCreatePostPath, paramMap);
		RequestBody body = RequestBody.create(JSON, json);	  
		Request request = new Request.Builder()
			      .url(departmentCreatePostApiUrl)
			      .post(body)
			      .build();
		String reposeString = null;
		try {
			Response response = okHttpClient.newCall(request).execute();
			reposeString = response.body().string();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return reposeString;
	}
	
	public String deleteDepartmentById(String departmentId) {
		String baseUrl = WorkWeixinConstants.baseUrl;
		String departmentDeleteGetPath = WorkWeixinConstants.departmentDeleteGetPath;
		
		String accessToken = "uwhr2YRko3cWg0e1SlxphMeL4AZ9crB9BTwEt99X9o1rECdX0q_zaPKikvTaiZw134sZumJvTQJ8oUZeyy3NY4cYGvgtTTfpsR_dpOC4z4-OGmCTL_DLBry3dPhorRpsGnh3RIk7Kk_pkYt2RljvWAQ2lhuXZFGmSbF8xqWIistdiw2CLkqZhu51B-yWk0R9hinaaEf_UHjHs3B4TF8urQ";
		Map<String,String> paramMap = new HashMap<String, String>();
		paramMap.put("access_token", accessToken);
		paramMap.put("id", departmentId);
		
		String departmentDeleteGetApiUrl = buildApiUrl(baseUrl, departmentDeleteGetPath, paramMap);
		
		Request request = new Request.Builder()
			      .url(departmentDeleteGetApiUrl)
			      .build();
		String reposeString = null;
		try {
			Response response = okHttpClient.newCall(request).execute();
			reposeString = response.body().string();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return reposeString;
	}
	
	private String buildApiUrl(String baseUrl, String path, Map<String,String> paramMap) {
		StringBuilder apiUrlBuilder = new StringBuilder();
		apiUrlBuilder.append(baseUrl);
		apiUrlBuilder.append(path);
		
		Set<Entry<String, String>> paramEntrySet = paramMap.entrySet();
		Iterator<Entry<String, String>> entryIter = paramEntrySet.iterator();
		int paramCount = 0;
		while(entryIter.hasNext()) {
			Entry<String, String> entry = entryIter.next();
			paramCount++;
			
			if(paramCount == 1) {
				apiUrlBuilder.append("?");
			} else {
				apiUrlBuilder.append("&");
			}
			
			String key = entry.getKey();
			String value = entry.getValue();
			apiUrlBuilder.append(key);
			apiUrlBuilder.append("=");
			apiUrlBuilder.append(value);
		}
		
		return apiUrlBuilder.toString();
	}
}
